package com.klod.api

import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import com.klod.config.AppConfig.MY_CLAIM
import com.klod.data.mapping.UserBean
import com.klod.data.services.UserServices
import com.klod.ext.responseFail
import com.klod.ext.responseSuccess
import com.klod.ext.toDateTimeString
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.auth.jwt.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import org.koin.java.KoinJavaComponent.inject
import java.time.Instant

fun Application.configureLoginRegisterApi() {

    val services by inject<UserServices>(UserServices::class.java)

    val secret = environment.config.property("jwt.secret").getString()
    val issuer = environment.config.property("jwt.issuer").getString()
    val audience = environment.config.property("jwt.audience").getString()


    routing {
        route("/user") {
            post("/login") {
                val user = call.receive<UserBean>()
                // Check username and password
                // ...
                if (services.checkLogin(user)) {

                    val token = JWT.create()
                        .withAudience(audience)
                        .withIssuer(issuer)
                        .withClaim(MY_CLAIM, user.account)
                        .withExpiresAt(Instant.MAX)
                        .sign(Algorithm.HMAC256(secret))
                    call.respond(token.responseSuccess())
                } else {
                    call.respond("帐号或密码错误".responseFail())
                }


            }
            post("/register") {
                //这是Get获取Query的from-data方法
//                call.parameters["id"]?.toInt() ?: -1
                //这是Post获取body的from-data方法
//                val formParameters = call.receiveParameters()
//                val username = formParameters["username"].toString()
//                call.respondText("The '$username' account is created")
                val user = call.receive<UserBean>().apply {
                    type = "0"
                    createDate = System.currentTimeMillis().toDateTimeString()
                }
                // Check username and password
                // ...

                if (services.register(user)) {

                    val token = JWT.create()
                        .withAudience(audience)
                        .withIssuer(issuer)
                        .withClaim(MY_CLAIM, user.account)
                        .withExpiresAt(Instant.MAX)
                        .sign(Algorithm.HMAC256(secret))

                    call.respond(token.responseSuccess())
                } else {
                    call.respond("该帐号已存在".responseFail())
                }


            }



            authenticate("auth-jwt") {
                get("/hello") {
                    val header = call.request.header(HttpHeaders.Authorization)
                    println(header)
                    val principal = call.principal<JWTPrincipal>()
                    val username = principal!!.payload.getClaim(MY_CLAIM).asString()
//                    val expiresAt = principal.expiresAt.toString()
                    call.respondText("Hello, $username! Token is forever")
                }

                get("/userinfo") {
//                call.respond("ID参数错误".responseFail())
                    val id = call.receiveParameters()["id"]?.toIntOrNull()?:-1
                    if(id==-1) call.respond("ID参数错误".responseFail())
                    val data = services.findById(id)?.apply { password = null }
                    call.respond(data.responseSuccess())
                }
            }
        }
    }

}